<template>
    <XTable ref='tableRef' :api='merchantPaginationApi' :columns='columns'>
        <template #toolBar>
            <router-link to='/merchant/add/'>
                <el-button type='primary' size='mini'>新增</el-button>
            </router-link>
        </template>

        <template #withdrawalRate='{value}'>{{value}}%</template>
        <template #status='{value}'>
            <span :class='{"color-forbidden" : value == 0}'>{{MERCHANT_STATUS[value]}}</span>
        </template>
        <template #area='{row}'>
            {{(row.province || '') + (row.city || '') + (row.district || '')}}
        </template>
        <template #action='{row}'>
            <template v-if='row'>
                <XRequestButton isConfirm :confirmText='row.status == 0 ? "确定启用该商户吗" : "确定禁用该商户吗"' :click='() => toggleMerchantStatus(row)'>
                    <el-button type='text'>{{row.status == 0 ? '启用' : '禁用'}}</el-button>
                </XRequestButton>
                <router-link class='m-l-5' :to='"/merchant/edit/" + row.merchantId'>
                    <el-button type='text'>编辑</el-button>
                </router-link>
            </template>
        </template>
    </XTable>
</template>

<script lang='ts' setup>
    import { onActivated, ref } from 'vue'
    import { merchantPaginationApi, toggleMerchantStatusApi } from '../../api/merchant'
    import { MERCHANT_STATUS } from '../../config'
    import { ElMessage } from 'element-plus'

    const columns:Column[] = [
        {title : '商户名称', dataIndex : 'merchantName', inFilter : true},
        {title : '账号', dataIndex : 'account', inFilter : true},
        {title : '账号状态', dataIndex : 'status'},
        {title : '提现费率', dataIndex : 'withdrawalRate'},
        {title : '联系人', dataIndex : 'contact'},
        {title : '联系电话', dataIndex : 'phone'},
        {title : '所属地区', dataIndex : 'area'},
        {title : '详细地址', dataIndex : 'address'},
    ]

    async function toggleMerchantStatus(row:any) {
        const res = await toggleMerchantStatusApi(row.merchantId, row.status)
        if(res) {
            row.status = Number(!row.status)
        }else {
            ElMessage.error!('请求失败')
        }
    }

    const tableRef = ref()
    const isFirst = ref(true)

    onActivated(() => {
        if(isFirst.value) {
            isFirst.value = false
        }else {
            tableRef.value.load()
        }
    })

</script>